/**
 * yeganaaa@163.com
 * author: (مۇختەرجان مەخمۇت) muhtaer mahmood
 * 10/13/2019, 1:40:26 PM GMT+06:00
 */



import {RpcMetaData, RpcMetaType} from "./Rpc";

export function isNodeRuntime() {
    let isNode = false
    if (typeof process === 'object') {
        if (typeof process.versions === 'object') {
            if (typeof process.versions.node !== 'undefined') {
                isNode = true
            }
        }
    }
    return isNode
}

export function getMetaDataObject(obj: any): RpcMetaData {
    function getAllFunctions(_obj: any): Array<string> {
        const functions = new Array<string>()
        if (_obj == null) {
            console.log(obj)
        }
        if (_obj.__proto__.constructor.name == "Object"){
            for (let prop in _obj) {
                if (typeof(_obj[prop]) != "function") continue
                if (prop.startsWith("_")) continue
                functions.push(prop)
            }
        }
        else {
            let proto = Reflect.getPrototypeOf(_obj)
            proto = Object.getOwnPropertyNames(proto) as Array<any>
            (proto as Array<any>).forEach(prop => {
                if (prop == "constructor") return
                if (prop.startsWith("_")) return
                functions.push(prop)
            })
        }
        return functions;
    }
    const metaData = new RpcMetaData("", RpcMetaType.Module)
    const functions = getAllFunctions(obj)
    for (let prop in obj) {
        if (prop.startsWith("_")) continue
        if (functions.filter(fn => fn == prop).length > 0) continue
        let member = obj[prop]
        if (typeof(member) === "object") {
            const module = getMetaDataObject(member)
            module.name = prop
            metaData.modules.push(module)
        }
    }
    functions.forEach(fn => {
        metaData.modules.push(new RpcMetaData((fn)))
    })
    return metaData
}